from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from datetime import datetime
from staff.models import *
from django.http import HttpResponseRedirect, HttpResponse
import random

def redirect(request, url):
    return HttpResponseRedirect(url)

def index(request):
    return render_to_response('staff/home.html', {'request':request, 'styles':['staff_home.css'], 'scripts':[]})

def clients(request):
    request.clients = Client.objects.all()
    return render_to_response('staff/clients.html', {'request':request, 'styles':['staff_clients.css']})

def clients_detail(request, id_cl):
    from exchanges.models import *
    request.client = Client.objects.get(id=id_cl)
    request.sales = Sale.objects.filter(client=request.client).order_by('-made')
    request.expended = 0
    request.debt = 0
    for s in request.sales:
        articles = ArticleSold.objects.filter(sale=s)
        for a in articles:
            c = a.item.sale_price * a.item.currency.multiplier
            request.expended += c
            if not s.payed:
                request.debt += c
        vinyls = VinylSold.objects.filter(sale=s)
        for v in vinyls:
            c = v.quantity * v.vinyl.price * v.vinyl.currency.multiplier
            request.expended += c
            if not s.payed:
                request.debt += c
        wheels = WheelSold.objects.filter(sale=s)
        for w in wheels:
            c = w.price * w.currency.multiplier
            request.expended += c
            if not s.payed:
                request.debt += c
    payments = Payment.objects.filter(client=request.client, taken=False)
    for p in payments:
        request.debt -= p.quantity * p.currency.multiplier
    return render_to_response('staff/clients_detail.html', {'request':request, 'styles':['staff_clients.css'], 'scripts':['tools.js', 'reports.js']})

def clients_payment(request, id_cl):
    from exchanges.models import *
    request.client = Client.objects.get(id=id_cl)
    request.sales = Sale.objects.filter(client=request.client, payed=False).order_by('-made')
    request.partial_debt = 0
    request.sales_total = []
    request.sales_index = []
    for s in request.sales:
        cur_sale = 0
        articles = ArticleSold.objects.filter(sale=s)
        for a in articles:
            cur_sale += a.item.sale_price * a.item.currency.multiplier
        vinyls = VinylSold.objects.filter(sale=s)
        for v in vinyls:
            cur_sale += v.quantity * v.vinyl.price * v.vinyl.currency.multiplier
        wheels = WheelSold.objects.filter(sale=s)
        for w in wheels:
            cur_sale += w.price * w.currency.multiplier
        request.sales_total.append(cur_sale)
        request.sales_index.append(int(s.id))
        request.partial_debt += cur_sale
    pay_done_before = 0
    pays = Payment.objects.filter(client=request.client, taken=False)
    for p in pays:
        pay_done_before += p.quantity * p.currency.multiplier
    request.pay_done_before = pay_done_before
    request.total_debt = request.partial_debt - pay_done_before
    request.payments = Payment.objects.filter(client=request.client, taken=False)
    request.payments_done = Payment.objects.filter(client=request.client, taken=True).order_by('-date')
    request.currencies = Currency.objects.all()
    return render_to_response('staff/clients_payment.html', {'request': request, 'styles': ['staff_clients.css'], 'scripts':['tools.js', 'reports.js']})

def clients_pay(request, id_cl):
    from exchanges.models import *
    cli = Client.objects.get(id=id_cl)
    qty = float(request.POST['pay_quantity'])
    cur = Currency.objects.get(id=request.POST['pay_quantity_currency'])

    pay_done_before = float(0)
    pays = Payment.objects.filter(client=cli, taken=False)
    for p in pays:
        pay_done_before += float(p.quantity) * float(p.currency.multiplier)
        p.quantity = 0
        p.taken = True
        p.save()

    qty += float(pay_done_before) / float(cur.multiplier)

    # In case the paiment was good enough for a sale
    ok = False
    total_debt = 0
    sales = Sale.objects.filter(client=cli, payed=False).order_by('-made')
    for s in sales:
        cur_sale = 0
        articles = ArticleSold.objects.filter(sale=s)
        for a in articles:
            cur_sale += a.item.sale_price * a.item.currency.multiplier
        vinyls = VinylSold.objects.filter(sale=s)
        for v in vinyls:
            cur_sale += v.quantity * v.vinyl.price * v.vinyl.currency.multiplier
        wheels = WheelSold.objects.filter(sale=s)
        for w in wheels:
            cur_sale += w.price * w.currency.multiplier
        total_debt += cur_sale
        if float(cur_sale) == float(qty) * float(cur.multiplier):
            s.payed = True
            s.save()
            ok = True
            break
    
    # If the client is paying all debts
    if not ok:
        if float(total_debt) <= float(qty) * float(cur.multiplier):
            for s in sales:
                s.payed = True
                s.save()
            ok = True
            qty = total_debt
        else:
            # If client is paying more than one debts
            for s in sales:
                cur_sale = 0
                articles = ArticleSold.objects.filter(sale=s)
                for a in articles:
                    cur_sale += a.item.sale_price * a.item.currency.multiplier
                vinyls = VinylSold.objects.filter(sale=s)
                for v in vinyls:
                    cur_sale += v.quantity * v.vinyl.price * v.vinyl.currency.multiplier
                wheels = WheelSold.objects.filter(sale=s)
                for w in wheels:
                    cur_sale += w.price * w.currency.multiplier
                if float(cur_sale) < float(qty) * float(cur.multiplier):
                    s.payed = True
                    s.save()
                    aux_cur = Currency.objects.get(id=1)
                    n_payment = Payment(date=datetime.now(), client=cli, quantity=cur_sale, currency=aux_cur, taken=True)
                    n_payment.save()
                    log = Log(id_user=request.user, action=24, id_action=n_payment.id, datetime=datetime.now())
                    log.save()
                    qty -= float(cur_sale) / float(cur.multiplier)
            ok = False

    n_payment = Payment(date=datetime.now(), client=cli, quantity=qty, currency=cur, taken=ok)
    n_payment.save()
    log = Log(id_user=request.user, action=24, id_action=n_payment.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/staff/clients/' + str(cli.id) + '/payment/')
        

def clients_register(request):
    ok = True
    while ok:
        name = u'user%d' % (random.randint(9, 999999))
        aux_user = User.objects.filter(username__exact=name)
        ok = aux_user.count() > 0

    nu = User(username=name, first_name=request.POST['firstname'], last_name=request.POST['lastname'], is_active=False)
    nu.save()
    client = Client(user=nu, nit=request.POST['nit'])
    client.save()
    log = Log(id_user=request.user, action=8, id_action=client.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/staff/clients/')

def vendors(request):
    request.vendors = Vendor.objects.all()
    request.vendor = request.session['vendor']
    return render_to_response('staff/vendors.html', {'request':request, 'styles':['staff_clients.css']})

def vendors_register(request):
    nv = User(first_name=request.POST['firstname'], last_name=request.POST['lastname'], username=request.POST['username'], is_active=True)
    nv.set_password(request.POST['password'])
    nv.save()
    vendor = Vendor(user=nv, is_owner=False)
    vendor.save()
    log = Log(id_user=request.user, action=18, id_action=vendor.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/staff/vendors/')

def vendors_delete(request, id_vendor):
    v = Vendor.objects.get(id=id_vendor)
    u = v.user
    log = Log(id_user=request.user, action=19, id_action=v.id, datetime=datetime.now())
    v.delete()
    u.delete()
    log.save()
    return redirect(request, '/staff/vendors/')

def providers(request):
    request.providers = Provider.objects.all()
    return render_to_response('staff/providers.html', {'request':request, 'styles':['staff_clients.css']})

def providers_register(request):
    np = User(first_name=request.POST['firstname'], last_name=request.POST['lastname'], is_active=False)
    np.save()
    np.username = "%s%d" % (np.first_name, np.id)
    np.save()
    provider = Provider(user=np)
    provider.save()
    log = Log(id_user=request.user, action=19, id_action=provider.id, datetime=datetime.now())
    log.save()
    return redirect(request, '/staff/providers/')
    

